package com.downbox.service.impl;

import com.downbox.config.GlobalExceptionHandler.BusinessException;
import com.downbox.domain.MoodOption;
import com.downbox.domain.UserMoodDaily;
import com.downbox.dto.SaveMoodsReq;
import com.downbox.repository.MoodOptionRepository;
import com.downbox.repository.UserMoodDailyRepository;
import com.downbox.service.MoodService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 情绪服务实现类
 */
@Service
public class MoodServiceImpl implements MoodService {

    @Autowired
    private MoodOptionRepository moodOptionRepository;

    @Autowired
    private UserMoodDailyRepository userMoodDailyRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<String> getMoodOptions() {
        return moodOptionRepository.findAllByOrderBySortNoAsc().stream()
                .map(MoodOption::getCode)
                .collect(Collectors.toList());
    }

    @Override
    public void saveUserMoods(Long userId, SaveMoodsReq req) {
        // 验证情绪选项是否有效
        List<String> validMoods = getMoodOptions();
        for (String mood : req.getMoods()) {
            if (!validMoods.contains(mood)) {
                throw new BusinessException(400, "无效的情绪选项: " + mood);
            }
        }

        try {
            String moodsJson = objectMapper.writeValueAsString(req.getMoods());
            LocalDate today = LocalDate.now();
            
            UserMoodDaily userMoodDaily = userMoodDailyRepository.findByUidAndDate(userId, today)
                    .orElseGet(() -> {
                        UserMoodDaily newRecord = new UserMoodDaily();
                        newRecord.setUid(userId);
                        newRecord.setDate(today);
                        return newRecord;
                    });
            
            userMoodDaily.setMoodsJson(moodsJson);
            userMoodDailyRepository.save(userMoodDaily);
        } catch (JsonProcessingException e) {
            throw new BusinessException(500, "保存情绪失败");
        }
    }

    @Override
    public List<String> getUserTodayMoods(Long userId) {
        LocalDate today = LocalDate.now();
        return userMoodDailyRepository.findByUidAndDate(userId, today)
                .map(userMoodDaily -> {
                    try {
                        return objectMapper.readValue(userMoodDaily.getMoodsJson(), List.class);
                    } catch (JsonProcessingException e) {
                        return List.of();
                    }
                })
                .orElse(List.of());
    }
}